﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// DBHelper 的摘要说明
/// </summary>
public class DBHelper
{
    public DBHelper()
    {
    }

    public static string connstr = "Server=.;User Id=sa;Pwd=123;DataBase=Hospital";
    public static SqlConnection conn=null;
    private static void InitConnection()
    {
        if (conn == null)
        {
            conn = new SqlConnection(connstr);
        }
        if (conn.State == ConnectionState.Broken)
        {
            conn.Close();
            conn.Open();
        }
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }    
    }
    public static int GetNonQuery(string sql)    //增删改
    {
        InitConnection();
        SqlCommand comm = new SqlCommand(sql, conn);
        int n=comm.ExecuteNonQuery();
        conn.Close();
        return n;
    }
    public static SqlDataReader GetDataReader(string sql)   //查询，获取记录中的数据
    {
        InitConnection();
        SqlCommand comm = new SqlCommand(sql, conn);
        SqlDataReader reader = comm.ExecuteReader();     
        return reader;    
    }
    public static object GetScalar(string sql)   //查询聚合函数
    {
        InitConnection();
        SqlCommand comm = new SqlCommand(sql, conn);
        object n = comm.ExecuteScalar();
        conn.Close();
        return n;
    }

    public static DataSet GetDataSet(string sql)
    {
        DataSet ds = new DataSet();
        InitConnection();
        SqlDataAdapter da = new SqlDataAdapter(sql,conn);
        da.Fill(ds);
        return ds;
    }

    public static DataTable GetDataTable(string sql)
    { 
        DataSet ds = new DataSet();
        ds=GetDataSet(sql);
        return ds.Tables[0];
    }
}